package com.disruptor.akka;

import akka.actor.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.concurrent.duration.Duration;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * Created by mengdexuan on 2017/9/20 17:13.
 */
public class Akka {

	private static Logger log = LoggerFactory.getLogger(Akka.class);

	private static final ActorSystem actorSystem = ActorSystem.create("test");
	private static final Inbox inbox = Inbox.create(actorSystem);
	private static ActorRef worker = actorSystem.actorOf(Props.create(MyWork.class), "worker");

	static {
		inbox.watch(worker);
		receive();
	}

	public static void send(MyWork.Msg msg){
		inbox.send(worker,msg);
	}

	private static void receive(){

		try {
			while (true){
				Object msg = inbox.receive(Duration.create(4, TimeUnit.SECONDS));
				if (msg==MyWork.Msg.CLOSE){
					log.info("my worker is closing...");
				}else if (msg instanceof Terminated){
					log.info("my worker terminated...");
					break;
				}
			}
		} catch (TimeoutException e) {
			e.printStackTrace();
		}
	}


}
